package com.cast.health.controller;

import com.cast.health.entity.PageResult;
import com.cast.health.entity.QueryPageBean;
import com.cast.health.entity.Result;
import com.cast.health.pojo.Setmeal;
import com.cast.health.service.SetmealService;
import com.cast.health.uitls.MessageConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;


@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    @Autowired
    private SetmealService setmealService;

    @Value("${reggie.path}")
    private String basePath;


    /**
     * 分页查询
     *
     * @param queryPageBean
     * @return
     */
    @PostMapping("/findPage.do")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        //检查参数
        if (queryPageBean.getCurrentPage() <= 0 || queryPageBean.getPageSize() <= 0) {
            return null; //参数非法
        }
        PageResult setmeal = setmealService.findPageSetmeal(queryPageBean);

        if (setmeal == null) {
            return null;
        }
        return setmeal;
    }

    /**
     * 上传图片
     *
     * @param imFile
     * @return
     */
    @PostMapping("/upload.do")
    public Result upload(@RequestParam("imgFile") MultipartFile imFile) {

        try {
            //得到原始上传名字
            String name = imFile.getOriginalFilename();
            //截取后缀
            String sname = name.substring(name.lastIndexOf("."));

            //uuid得到新的前缀名字
            String fname = UUID.randomUUID().toString().replace("-", "") + sname;

            //创建一个目录对象
            File dir = new File(basePath);
            //判断当前目录是否存在
            if (!dir.exists()) {
                //目录不存在，需要创建
                dir.mkdirs();
            }

            try {
                //将临时文件转存到指定位置
                imFile.transferTo(new File(basePath + fname));
            } catch (IOException e) {
                e.printStackTrace();
            }
            return new Result(true, fname);

        } catch (Exception e) {
            return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);
        }
    }

    /**
     * 添加数据
     *
     * @param setmeal
     * @return
     */
    @PostMapping("/add.do")
    public Result add(@RequestBody Setmeal setmeal,Integer[] checkgroupIds) {
        //检查参数
        if (setmeal == null) {
            return new Result(false, "参数错误!");
        }
        //添加
        boolean save = setmealService.addSetmeal(setmeal,checkgroupIds);
        //判断
        if (save == false) {
            return new Result(false, MessageConstant.ADD_SETMEAL_FAIL);
        }

        return new Result(true, MessageConstant.ADD_SETMEAL_SUCCESS);
    }


}
